package kr.re.etri.snsenabler.client;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import kr.re.etri.snsenabler.client.service.SnsEnablerService;
import kr.re.etri.snsenabler.client.service.SnsEnablerServiceAsync;
import kr.re.etri.snsenabler.shared.Data;
import kr.re.etri.snsenabler.shared.ServiceResponse;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.sencha.gxt.widget.core.client.box.AlertMessageBox;

public class SnsEnabler implements EntryPoint, Controller {

	private final SnsEnablerServiceAsync snsEnablerService = GWT.create(SnsEnablerService.class);
	private final Logger logger = Logger.getLogger(getClass().getName());

	private Login login;

	@Override
	public void onModuleLoad() {
		GWT.log(GWT.getModuleBaseURL());
		GWT.log(GWT.getHostPageBaseURL());
		GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
			public void onUncaughtException(Throwable e) {
				Window.alert("Error: " + e.getMessage());
				logger.log(Level.SEVERE, e.getMessage(), e);
				e.printStackTrace();
			}
		});

		Window.enableScrolling(false);

		Map<String, List<String>> parameterMap = Window.Location.getParameterMap();
		Iterator<String> iterator = parameterMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			logger.info(key + ": " + parameterMap.get(key));
		}

		snsEnablerService.getUser(new AsyncCallback<ServiceResponse>() {
			public void onFailure(Throwable caught) {
				logger.log(Level.SEVERE, caught.getMessage(), caught);
				AlertMessageBox messageBox = new AlertMessageBox("Alert", "Access Denied");
				messageBox.show();
			}

			public void onSuccess(ServiceResponse result) {
				userLoaded(result);
			}
		});
	}

	private void userLoaded(ServiceResponse result) {
		if (result == null || result.isFailed()) {
			login = new Login(this);
			login.getWindow().setContainer(RootPanel.get().getElement());
			login.getWindow().show();
		} else {
			setUser(result.getData());
		}
	}

	@Override
	public void setUser(Data user) {
		if (login != null) {
			login.getWindow().hide();
		}

		AuthoringTool inquiry = new AuthoringTool(user);
		RootPanel.get().add(inquiry.getContainer());
	}
}
